const { Op } = require("sequelize");

const User = require('../model/user.model')

//添加用户入库 ---增
class operationUser {
	async addUser({ user_name, password, stuNum, phone }) {
		const res = await User.create({
			user_name,
			password,
			stuNum,
			phone,
			is_admin: 0
		})
		return res.dataValues

	}
	async getUserInfo({ id, user_name, stuNum, phone }) {
		const whereOpt = {}

		id && Object.assign(whereOpt, { id })
		user_name && Object.assign(whereOpt, { user_name })
		stuNum && Object.assign(whereOpt, { stuNum })
		phone && Object.assign(whereOpt, { phone })

		const res = await User.findOne({
			// attributes: ['id', 'user_name', 'stuNum', 'phone'],
			where: whereOpt,
		})
		return res ? res.dataValues : null
	}

	async getAllUsers() {
		return User.findAll({
			where: {
				is_admin: false
			}
		})
	}

	async getUserInfoById(id) {
		return User.findOne({
			where: {
				id
			}
		})
	}

	async modifyUserInfo({ user_name, stuNum, phone }, id) {
		const whereOpt = {}

		user_name && Object.assign(whereOpt, { user_name })
		stuNum && Object.assign(whereOpt, { stuNum })
		phone && Object.assign(whereOpt, { phone })

		User.update(whereOpt, {
			where: {
				id
			}
		});
	}

	async fuzzyQuery({ id, user_name, stuNum, phone }) {

		const res = await User.findAll({
			where: {
				[Op.or]: [
					{
						id:
						{
							[Op.like]: '%' + id + '%',
						}
					},
					{
						user_name:
						{
							[Op.like]: '%' + user_name + '%',
						}
					},
					{
						stuNum:
						{
							[Op.like]: '%' + stuNum + '%',
						}
					},
					{
						phone:
						{
							[Op.like]: '%' + phone + '%',
						}
					},
				]
			},
		})
		return res
	}

}
module.exports = new operationUser()